<template>
  <div class="travel-expense">
    <search-header :title="reportsTitle" @on-search="search"></search-header>
    <div class="title-list fix">
      <div class="fl tm fix">
        <div class="fl tm-lf"><i class="iconfont icon-rili1"></i><span>{{year}}</span>年</div>
        <div class="fl tm-rt"><span>{{month > 9 ? month : '0' + month}}</span>月</div>
      </div>
      <div class="fr tt fix">
        <div class="fl w33">
          <div class="nub"><i class="iconfont icon-chalvzhichu"></i><span>{{cost?cost/100:cost}}</span>元</div>
          <p>差旅总支出</p>
        </div>
        <div class="fl w33">
          <div class="nub"><i class="iconfont icon-huanbizengchang"></i><span>{{increasePercent}}</span></div>
          <p>环比增长</p>
        </div>
        <div class="fl w33">
          <div class="nub"><i class="iconfont icon-yusuanxiaohao"></i><span>{{budgetCostPercent}}</span></div>
          <p>预算消耗率</p>
        </div>
      </div>
    </div>
    <div class="content">
      <tabs v-model="curTab">
        <span slot="extra" class="tab-left">结构分析</span>
        <tabPane label="订单类型" name="orderType">
          <div class="fix">
            <div class="fl orderTab">
              <div class="orderType">
                <Table class="tabTop" height="360" :columns="orderTypeColumns" :data="orderTypeData"></Table>
              </div>
            </div>
            <div class="fr chart">
              <div>
                <div id="chart-order-type" :style="{width:'480px',height:'360px'}"></div>
              </div>
            </div>
          </div>
        </tabPane>
        <tabPane label="出行类别" name="travelType">
          <div class="fix">
            <div class="fl orderTab">
              <div class="orderType">
                <Table class="tabTop" height="360" :columns="travelTypeColumns" :data="travelTypeData"></Table>
              </div>
            </div>
            <div class="fr chart">
              <div>
                <div id="chart-travel-type" :style="{width:'480px',height:'360px'}"></div>
              </div>
            </div>
          </div>
        </tabPane>
        <tabPane label="单位统计" name="orgChild" v-if="orgChildrenData.length > 0">
          <div class="fix orgChild">
            <div class="fl chart">
              <div id="chart-org-child" :style="{width:'480px',height:(orgChildrenData.length * 35 + 20)+'px'}"></div>
            </div>
            <div class="fr chart">
              <div id="chart-org-month" :style="{width:'480px',height:'360px'}"></div>
            </div>
          </div>
        </tabPane>
      </tabs>
    </div>
    <div id="footer"><p class="copyright">本报表统计指定期间内产生的所有差旅订单，与当期财务入账的【差旅费用】口径并非一致。</p></div>
  </div>
</template>
<script>
  import echarts from 'echarts';
  import SearchHeader from '@/components/bi/search-header.vue';
  import bi from '@/data/bi.js';
  export default {
    components: {SearchHeader},
    data() {
      return {
        curTab: 'orderType',
        reportsTitle: '差旅支出分析',
        year: null,
        month: null,
        cost: null,//总支出
        increasePercent: null,//环比增长
        budgetCostPercent: null,//预算消耗率
        orderTypeColumns: [
          {
            title: '订单类型',
            width: 140,
            key: 'name',
            /*renderHeader: (h, index) => {
             var column = index.column;
             return h('div', {
             style: {
             color: '#237bff'
             }
             }, column.title);
             }*/
          },
          {
            title: '上月',
            key: 'lastMoney',
            align: 'right'
          },
          {
            title: '当月',
            key: 'currentMoney',
            align: 'right'
          },
          {
            title: '当月增长率',
            key: 'increase',
            align: 'center'
          }
        ],
        travelTypeColumns: [
          {
            title: '出行类别',
            width: 140,
            key: 'name',
          },
          {
            title: '上月',
            key: 'lastMoney',
            align: 'right'
          },
          {
            title: '当月',
            key: 'currentMoney',
            align: 'right'
          },
          {
            title: '当月增长率',
            key: 'increase',
            align: 'center'
          }
        ],
        orderTypeData: [],//订单类型数据
        travelTypeData: [],//出行类别数据
        travelTypeName: {},
        showMonths: [],
        monthOrderTypeData: {},//订单类型近6月数据
        monthTravelTypeData: {},//出行类型近6月数据
        orgChildrenData: [],//下级组织数据
        chartOrderType: null,
        chartTravelType: null,
        chartOrgChild: null,
        chartOrgMonth: null,
        curOrgChildName: null
      };
    },
    mounted() {
      var curDate = new Date();
      this.year = curDate.getFullYear();
      this.month = curDate.getMonth() + 1;

      this.chartOrderType = echarts.init(document.getElementById('chart-order-type'));
      this.chartTravelType = echarts.init(document.getElementById('chart-travel-type'));
    },
    methods: {
      search(params){
        //清空当前部门
        this.curOrgChildName = null;
        var date = params.searchDate || new Date();
        this.showChartLoading();
        bi.getTravelCost({
          orgId: params.orgId,
          year: date.getFullYear(),
          month: date.getMonth() + 1
        }).then(res => {
          this.closeChartLoading();
          if (res.code == '0') {
            this.initData(res.data);
          } else {
            this.$Message.error('查询异常信息:' + (res.msg || res.code));
          }
        });
      },
      showChartLoading(){
        this.chartOrderType && this.chartOrderType.showLoading();
        this.chartTravelType && this.chartTravelType.showLoading();
        this.chartOrgChild && this.chartOrgChild.showLoading();
        this.chartOrgMonth && this.chartOrgMonth.showLoading();
      },
      closeChartLoading(){
        this.chartOrderType && this.chartOrderType.hideLoading();
        this.chartTravelType && this.chartTravelType.hideLoading();
        this.chartOrgChild && this.chartOrgChild.hideLoading();
        this.chartOrgMonth && this.chartOrgMonth.hideLoading();
      },
      initData(data){
        this.year = data.year;
        this.month = data.month;
        this.cost = data.cost;
        this.increasePercent = data.increasePercent || '--';
        this.budgetCostPercent = data.budgetCostPercent || '--';

        //订单类型数据
        var orderTypeData = [];
        if (data.orderTypeData) {
          data.orderTypeData.forEach(item => {
            var last = item.lastMonthMoney, cur = item.currentMonthMoney;
            var increase = this.calcIncrease(last, cur);
            orderTypeData.push({
              name: item.name,
              lastMoney: last ? (last / 100).toFixed(2) : 0,
              currentMoney: cur ? (cur / 100).toFixed(2) : 0,
              increase: increase ? increase + '%' : '-'
            });
          });
        }
        this.orderTypeData = orderTypeData;

        //出行类别数据
        var travelTypeData = [];
        if (data.travelTypeData) {
          data.travelTypeData.forEach(item => {
            var last = item.lastMonthMoney, cur = item.currentMonthMoney;
            var increase = this.calcIncrease(last, cur);
            travelTypeData.push({
              name: item.name,
              lastMoney: last ? (last / 100).toFixed(2) : 0,
              currentMoney: cur ? (cur / 100).toFixed(2) : 0,
              increase: increase ? increase + '%' : '-'
            });
            this.travelTypeName[item.type] = item.name;
          });
        }
        this.travelTypeData = travelTypeData;

        //显示月份数据
        if (data.months) {
          var showMonths = [];
          data.months.forEach(ym => {
            var m = moment(ym, 'YYYY-MM').month();
            showMonths.push(this.cnTxt[m] + '月');
          });
          this.showMonths = showMonths;
        } else {
          console.error('展示月份数据异常');
        }

        this.monthOrderTypeData = data.monthOrderTypeData || {};
        this.monthTravelTypeData = data.monthTravelTypeData || {};
        this.orgChildrenData = data.orgChildrenData || [];

        //初始化订单类型图表
        this.initOrderTypeChart();
        //初始化出行类别图表
        this.initTravelTypeChart();

        if (this.orgChildrenData.length > 0) {
          //延迟原因是下面初始化事件比下级单位dom显示要先执行
          setTimeout(() => {
            this.chartOrgChild = echarts.init(document.getElementById('chart-org-child'));
            //this.initOrgChildChart();
            //this.bindEvent();
            this.chartOrgMonth = echarts.init(document.getElementById('chart-org-month'));
            this.curOrgChildName = this.orgChildrenData[0].orgName;
            //echarts.connect([this.chartOrgChild, this.chartOrgMonth]);
          }, 100);
        }
      },
      initOrderTypeChart(){//订单类型目录数据
        var monthOrderTypeData = this.monthOrderTypeData;
        var typeConfig = {//各业务个性化配置
          10: {
            itemStyle: {
              color: '#e7a85d'
            },
            lineStyle: {
              color: '#e7a85d'
            }
          },
          11: {
            itemStyle: {
              color: '#a4ce68'
            },
            lineStyle: {
              color: '#a4ce68'
            }
          },
          12: {
            itemStyle: {
              color: '#5cc4de'
            },
            lineStyle: {
              color: '#5cc4de'
            }
          },
          other: {
            itemStyle: {
              color: '#929cce'
            },
            lineStyle: {
              color: '#929cce'
            }
          }
        };

        var series = [];
        for (var k in monthOrderTypeData) {
          var bizName = this.bizType[k];
          var se = {
            name: bizName,
            type: 'line',
            stack: '金额',
            data: this.moneyToFloat(monthOrderTypeData[k]),
            symbol: 'circle'
          };
          var speacialConfig = typeConfig[k];
          if (speacialConfig) {
            Object.assign(se, speacialConfig);
          }
          series.push(se);
        }

        var option = {
          title: {
            text: '',
            x: 'center',
            textStyle: {
              color: '#666',
              fontWeight: '500',
              fontSize: '16px'
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.showMonths,
            axisLine: {
              lineStyle: {
                color: '#999',
                width: '1px'
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            name: '支出金额',
            type: 'value',
            axisLine: {
              show: false,
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: false
            }
          },
          series: series
        };
        this.chartOrderType.setOption(option);

        //高亮显示
        /*this.chartOrderType.dispatchAction({
         type: 'highlight',
         dataIndex:2
         });*/
      },
      initTravelTypeChart(){
        var monthTravelTypeData = this.monthTravelTypeData;
        var lineColors = ['#e7a85d', '#a4ce68', '#5cc4de', '#929cce'];//不同的色块
        var series = [];
        var i = 0;
        for (var k in monthTravelTypeData) {
          var name = this.travelTypeName[k];
          var se = {
            name: name,
            type: 'line',
            stack: '金额',
            data: this.moneyToFloat(monthTravelTypeData[k]),
            symbol: 'circle',
            itemStyle: {
              color: lineColors[i]
            },
            lineStyle: {
              color: lineColors[i]
            }
          };
          series.push(se);
          i++;
        }

        var option = {
          title: {
            text: '',
            x: 'center',
            textStyle: {
              color: '#666',
              fontWeight: '500',
              fontSize: '16px'
            }
          },
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.showMonths,
            axisLine: {
              lineStyle: {
                color: '#999',
                width: '1px'
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            name: '支出金额',
            type: 'value',
            axisLine: {
              show: false,
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: false
            }
          },
          series: series
        };
        this.chartTravelType.setOption(option);
      },
      initOrgChildChart(){
        var orgChildrenData = this.orgChildrenData;
        var orgNames = [];
        var orgMoney = [];
        orgChildrenData.forEach(org => {
          var v1 = {
            value: org.orgName
          };
          var v2 = {
            value: org.money > 0 ? org.money / 100 : 0
          };
          if (org.orgName == this.curOrgChildName) {
            v1.textStyle = {
              color: '#3385ff',
              fontWeight: 'bolder'
            };
            v2.itemStyle = {
              color: '#3385ff'
            };
          }
          orgNames.push(v1);
          orgMoney.push(v2);
        });
        /*通过chart反转
         rgNames.reverse();
         orgMoney.reverse();*/
        var option = {
          /*title: {
           text: '',
           x: 'center',
           textStyle: {
           color: '#666',
           fontWeight: '500',
           fontSize: '16px'
           }
           },*/
          tooltip: {
            trigger: 'axis',
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            show: 'true',
            borderWidth: 0,
            backgroundColor: '#fff'
          },
          xAxis: {
            show: false,
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            splitNumber: 11,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            interval: 50,
            type: 'category',
            data: orgNames,
            triggerEvent: true,
            inverse: true
          },
          series: [
            {
              //name: '下级单位支出',
              type: 'bar',
              barMaxWidth: 17,
              data: orgMoney,
              itemStyle: {
                color: '#81b3ff'
              },
              label: {
                normal: {
                  show: true,
                  position: 'right',
                  formatter: '{c}元'
                }
              },
              /*emphasis: {//高亮设置
               itemStyle: {
               color: 'red'
               }
               }*/
            }
          ]
        };
        var chart = this.chartOrgChild;
        chart.setOption(option);
        this.bindEvent();
      },
      bindEvent(){
        var chartOrgChild = this.chartOrgChild;
        if (chartOrgChild) {
          chartOrgChild.off('click');
          chartOrgChild.on('click', params => {
            //console.log(params)
            if (params) {
              if (params.componentType == 'series') {
                this.curOrgChildName = params.name;
              } else if (params.componentType == 'yAxis') {
                this.curOrgChildName = params.value;
              }
            }
            //这句无效郁闷
            /*this.chartOrgChild.dispatchAction({
             type: 'highlight',
             seriesIndex: 0,
             dataIndex: 5,
             name:'技术部'
             })*/
          });
        }
      },
      initOrgMonthChart(){
        var data = [];
        this.showMonths.forEach(() => {
          //data.push(Math.random()*10000);
          data.push(0);
        });
        this.orgChildrenData.forEach(org => {
          if (org.orgName == this.curOrgChildName) {
            if (org.monthData && org.monthData.length > 0) {
              data = org.monthData;
            }
            return false;
          }
        });
        data = this.moneyToFloat(data);
        var min = 10000;
        data.forEach(d => {
          if (d > 0) {
            min = 0;
            return false;
          }
        });
        var option = {
          title: {
            text: '',
            x: 'center',
            textStyle: {
              color: '#666',
              fontWeight: '500',
              fontSize: '16px'
            }
          },
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>{c}元'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.showMonths,
            axisLine: {
              lineStyle: {
                color: '#999',
                width: '1px'
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            name: '【' + this.curOrgChildName + '】支出金额',
            type: 'value',
            axisLine: {
              show: false,
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: false
            },
            min: min
          },
          series: [
            {
              //name: 'monthData',
              type: 'line',
              stack: '支出金额',
              data: data,
              itemStyle: {
                color: '#e7a85d'
              },
              lineStyle: {
                color: '#e7a85d'
              },
              symbol: 'circle'
            }
          ]
        };
        this.chartOrgMonth.setOption(option);
      },
      calcIncrease(pre, current){//计算增长率
        if (!pre || !current) {
          return null;
        }
        return ((current - pre) / pre * 100).toFixed(2);
      },
      moneyToFloat(v){//分转元
        var rs = [];
        if (v) {
          v.forEach(item => {
            rs.push(item ? item / 100 : 0);
          });
        }
        return rs;
      },
      sumArr(arr){//加总数组
        var total = 0.0;
        if (arr) {
          arr.forEach(item => {
            if (item) {
              total += item;
            }
          });
        }
        return total;
      }
    },
    computed: {
      bizType(){
        return this.$store.state.bizType;
      },
      cnTxt(){
        return this.$store.state.cnTxt;
      }
    },
    watch: {
      month(val){
        var last = val - 1;
        if (last < 1) {
          last = this.year + '年12';
        }
        this.orderTypeColumns[1].title = this.travelTypeColumns[1].title = last + '月';
        this.orderTypeColumns[2].title = this.travelTypeColumns[2].title = val + '月';
      },
      orgChildrenData(data){
        if (data.length == 0) {
          this.curTab = 'orderType';
        }
      },
      curOrgChildName(name){
        if (this.chartOrgChild) {
          this.initOrgChildChart();
          if (name) {
            this.initOrgMonthChart();
          }
        }
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .travel-expense {
    height: 100%;
    width: 100%;
    padding: 20px;
    background-color: #f4f4f4;
  }

  .title-list {
    margin-top: 20px;
    .tm {
      height: 160px;
      width: 270px;
      text-align: center;
      vertical-align: middle;
      font-size: 14px;
      border-radius: 3px;
      overflow: hidden;
      .tm-lf {
        height: 160px;
        width: 110px;
        color: #FFFFFF;
        background-color: #3385ff;
      }
      .tm-rt {
        line-height: 160px;
        height: 160px;
        width: 160px;
        color: #3385ff;
        background-color: #e3eeff;
      }
      span {
        font-weight: bold;
        font-size: 30px;
      }
      .icon-rili1 {
        display: block;
        font-size: 36px;
        margin-top: 28px;
      }
    }
    .tt {
      height: 160px;
      background-color: #FFFFFF;
      width: calc(100% - 290px);
      border-radius: 3px;
      .w33 {
        width: 33.33%;
        display: inline-block;
        padding-left: 40px;
        .nub {
          margin-top: 32px;
          font-size: 14px;
          color: #333333;
          span {
            font-size: 30px;
            color: #333333;
          }
          .icon-rili {
            color: #EB7A77;
            font-size: 36px;
            margin-right: 16px;
          }
        }
        p {
          font-size: 18px;
          color: #666666;
          text-align: left;
          margin-left: 40px;
        }
      }
    }
  }

  .icon-chalvzhichu {
    color: #00aa90;
    font-size: 36px;
    margin-right: 16px;
  }

  .icon-huanbizengchang {
    color: #ffb11b;
    font-size: 36px;
    margin-right: 16px;
  }

  .icon-yusuanxiaohao {
    color: #eb7a77;
    font-size: 36px;
    margin-right: 16px;
  }

  .content {
    margin-top: 20px;
    padding: 20px;
    background-color: #FFFFFF;
    .tab-left {
      line-height: 35px;
      font-size: 14px;
      font-weight: bold;
    }
    .orderTab {
      width: calc(50% - 10px);
    }
    .chart {
      width: calc(50% - 10px);
    }
  }

  .mt20 {
    margin-top: 20px;
  }

  #footer .copyright {
    font-size: 12px;
    color: #666666;
    margin: 0 auto;
    width: 100%;
    text-align: center;
    padding: 20px 0;
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  .tabTop {
    border: none;
    .ivu-table:after {
      content: '';
      width: 0px;
      height: 100%;
      position: absolute;
      top: 0;
      right: 0;
      background-color: #dddee1;
      z-index: 3;
    }
    .ivu-table:before {
      content: '';
      width: 100%;
      height: 0px;
      position: absolute;
      left: 0;
      bottom: 0;
      background-color: #dddee1;
      z-index: 1;
    }
    th {
      background-color: #d6e7ff !important;
      font-weight: bold;
    }
    .ivu-table .tabTitle {
      background-color: #EB7A77;
      /*color: #3385ff;*/
    }
  }

  .ivu-tabs-nav {
    float: right !important;
  }

  .ivu-tabs-nav-right {
    float: left;
  }
</style>
